<?php 
namespace froyo\cherry\Db;
use froyo\cherry\Base\BaseCompoment;

class DbComment extends BaseCompoment{

	public $config = [];

	public $query;
	public $queryModel = null;

	public $connection;
	public $connectionModels = null;

    /**
     * @return mixed
     */
    public function getConfig($alias='',$key='')
    {

        $config = [];
    	if($alias)
    	{
    		if(isset($this->config[ $alias ]))
    		{
    			$config = $this->config[ $alias ];
    		}
    		elseif($alias == 'default')
    		{
    			$config = $this->config;
    		}
    	}
        else
        {
            $config = $this->config;
        }
        if($key)
        {
            return isset($config[$key])?$config[$key]:'';
        }
        return $config;
    }

    /**
     * @param mixed $config
     *
     * @return self
     */
    public function setConfig($config)
    {
        $this->config = $config;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getQuery()
    {
    	if(!$this->queryModel)
    	{
    		$class = $this->query;

    		if(!class_exists($class))
    		{
    			throw new \Exception("Not Exist Query Class");
    		}
    		$this->queryModel = new $class();
    	}
        return $this->queryModel;
    }


    /**
     * @return mixed
     */
    public function getConnection($alias='')
    {
    	if(!$alias)
    	{
    		$alias = 'default';
    	}

		if(isset($this->connectionModels[$alias]))
		{
			return $this->connectionModels[$alias];
		}
		else
		{
			
			$class = $this->connection;
    		if(!class_exists($class))
    		{
    			throw new \Exception("Not Exist Connection Class");
    		}

    		$connect = new $class();
    		if($connect)
    		{
    			$connect->setDbConfig($this->getConfig($alias));
    		}
    		$this->connectionModels[$alias] = $connect;
		}
		if(!isset($this->connectionModels[$alias]))
		{
			throw new \Exception("Get Connection Error");
		}

        return $this->connectionModels[$alias];
    }

    /**
     * @param mixed $connection
     *
     * @return self
     */
    public function setConnection($connection,$alias='')
    {
        $this->connectionModels[$alias] = $connection;

        return $this;
    }
}